package com.lxr.test5002;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;

import com.white.progressview.HorizontalProgressView;

/**
 * 类描述:[光感测试]
 * 说明:
 * @author: LXR
 * @Date: 2023/12/15 11:51
 */
public class LightSensorActivity extends Activity {
    private TextView mTvSensorNumber;
    private HorizontalProgressView mProgressBar;
    private SensorManager mSensorManager;
    private Sensor mSensor;
    private SensorEventListener mListener;
    private static final int MAX_LIGHT = 600;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_light_sensor);
        initView();
        initData();
    }

    private void initView() {
        mTvSensorNumber = (TextView) findViewById(R.id.tv_light_sensor_number);
        mProgressBar = (HorizontalProgressView) findViewById(R.id.pb_light_sensor);

    }

    private void initData() {
        mProgressBar.setMax(MAX_LIGHT);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        mListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                float value = event.values[0];
                mProgressBar.setProgress((int) value);
                mTvSensorNumber.setText("当前光线值：" + value + " lux");
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {

            }
        };
        mSensorManager.registerListener(mListener, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
    }

    protected void onDestroy() {
        super.onDestroy();
        //注销监听器
        if (mListener != null) {
            mSensorManager.unregisterListener(mListener);
        }
    }
}
